import Sanke from './Snake'
import Food from './Food'
import ScorePanel from './ScorePanel'
import Snake from './Snake'
// 游戏控制器控制其他所有类
class GameControl {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;
  direction: string = '';
  isLive = true;
  constructor() {
    this.snake = new Sanke()
    this.food = new Food()
    this.scorePanel = new ScorePanel(10,1)
    this.init()
  }
  init() {
    //  绑定键盘按下的事件
    document.addEventListener('keydown', this.keydownHandler.bind(this))
    this.run();
  
   
  }
  keydownHandler(event: KeyboardEvent) {
    {
      // 修改direction的值
      this.direction = event.key

    }
  }
  run() {
    /**
     * 根据方向来使蛇的位置发生改变
     */
    let X = this.snake.X
    let Y = this.snake.Y
    switch (this.direction) {
      case 'ArrowUp':
      case 'Up':
        Y -= 10; break
      case 'ArrowDown':
      case 'Down':
        Y += 10; break
      case 'ArrowRight':
      case 'Right':
        X += 10; break
      case 'ArrowLeft':
      case 'Left':
        X -= 10; break
    }
    this.checkEat(X, Y);
    try {
      this.snake.X = X
      this.snake.Y = Y
    }
    catch (e) {
      alert(e.message + 'Game Over')
      this.isLive = false
    }
    this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
  }
  checkEat(x: number, y: number) {
    if (x === this.food.X && y === this.food.Y) {
      // 食物进行重置
      this.food.change()
      // 分数增加
      this.scorePanel.addScore()
      // 蛇的身体增加
      this.snake.addBody()
    }
  }
}
export default GameControl;